package com.wise.schedule.sample2quartz.config;

import org.quartz.CronTrigger;
import org.quartz.impl.triggers.CronTriggerImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import java.util.ArrayList;
import java.util.List;

@Configuration
@Profile("sample2")
public class BaseConfig {
    private String triggerList = "scheduleTrigger";

    @Autowired
    private ApplicationContext applicationContext;

    @Bean
    public ThreadPoolTaskExecutor executor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(5);
        executor.setMaxPoolSize(10);
        executor.setQueueCapacity(5);
        return executor;
    }

    @Bean
    public SchedulerFactoryBean schedulerFactoryBean() {
        SchedulerFactoryBean bean = new SchedulerFactoryBean();
        bean.setTaskExecutor(executor());
        if (triggerList != null && !"".equals(triggerList)) {
            String[] triggers = triggerList.split(",");
            List<CronTrigger> list = new ArrayList<>();
            for (String triggerName : triggers) {
                CronTrigger trigger = (CronTriggerImpl) applicationContext.getBean(triggerName);
                list.add(trigger);
            }
            CronTrigger[] cronTriggers = new CronTrigger[list.size()];
            cronTriggers = list.toArray(cronTriggers);
            bean.setTriggers(cronTriggers);
        }
        return bean;
    }
}
